/**   
 * Copyright © 2019 eSunny Info. Tech Ltd. All rights reserved.
 * 
 * @Description:TODO(功能)
 * @className LoginFilter.java
 * @Package: com.erp.filter 
 * @author: yj   
 * @date: 2019年2月19日 上午10:02:43 
 */
package com.erp.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @className LoginFilter.java
 * @author yj
 * @Description:TODO(功能)
 * @Date 2019年2月19日
 */
public class LoginFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("---登陆拦截器初始化---");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		// 强转得到session
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession();
		String loginName = (String)session.getAttribute("loginName");
		// 获取访问路径
		String uri = request.getRequestURI();
		
		// 把路径统一转换为小写
		uri = uri.toLowerCase();
		
		if(uri.indexOf("index") == -1 && uri.indexOf("login") == -1 
				&& uri.indexOf("assets") == -1 && uri.indexOf("javascript") == -1) {
			PrintWriter out = response.getWriter();
			if(loginName == null) {
				out.write("<script>alert('对不起 , 请先登录.');location.href = '"+request.getContextPath()+"/index.jsp';</script>");
			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		System.out.println("---登陆拦截器销毁---");
	}

}
